package org.slg.oracleproject.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.slg.oracleproject.service.PermissionService;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限评估器：解析@PreAuthorize中的hasPermission表达式
 */
@Slf4j
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    private PermissionService permissionService;

    /**
     * 处理无资源ID的权限检查（如@PreAuthorize("hasPermission('', 'user:list')")）
     */
    @Override
    public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
        // 未登录或匿名用户直接拒绝
        if (auth == null || !auth.isAuthenticated()) {
            return false;
        }

        // 权限必须是字符串类型
        if (!(permission instanceof String)) {
            return false;
        }
        String targetPermission = (String) permission;

        // 提取用户角色（带ROLE_前缀）
        List<String> roles = auth.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        log.info("当前用户角色：{}", roles);

        // 查询角色对应的权限并校验
        List<String> userPermissions = permissionService.getPermissionsByRoles(roles);
        return userPermissions.contains(targetPermission);
    }

    /**
     * 处理有资源ID的权限检查（简化实现，复用无资源逻辑）
     */
    @Override
    public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
        return hasPermission(auth, targetType, permission);
    }
}